package cn.duckerkj.base.aop;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.duckerkj.base.annotation.Permissions;
import cn.duckerkj.pojo.base.SessionInfo;



public class MyHandlerInterceptor implements HandlerInterceptor   {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private NamedThreadLocal<Long>  startTimeThreadLocal = new NamedThreadLocal<Long>("StopWatch-StartTime");  

	

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		logger.info("afterCompletion");
	    long endTime = System.currentTimeMillis();//2、结束时间  
        long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）  
        long consumeTime = endTime - beginTime;//3、消耗的时间  
        if(consumeTime > 500) {//此处认为处理时间超过500毫秒的请求为慢请求  
            //TODO 记录到日志文件  
        	logger.error( String.format("%s consume %d millis", request.getRequestURI(), consumeTime)); 
        }       
	}


	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView model)
			throws Exception {
		// TODO Auto-generated method stub
		logger.info("postHandle");
		
	}


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		logger.info("preHandle");
		logger.info("URL=" + request.getRequestURL().toString());  
        logger.info("HTTP_METHOD=" + request.getMethod());  
        logger.info("IP=" + request.getRemoteAddr());  
        
        long beginTime = System.currentTimeMillis();//1、开始时间  
        startTimeThreadLocal.set(beginTime);//线程绑定变量（该数据只有当前请求的线程可见）
		HandlerMethod method = (HandlerMethod)handler;
		HttpSession session = request.getSession();
		
		SessionInfo sessionInfo = (SessionInfo) session.getAttribute("sessionInfo");
	    if(method.getMethod().isAnnotationPresent(Permissions.class)){
        	Permissions needVerify = method.getMethod().getAnnotation(Permissions.class);
        	//如果没有@EmployeeVerify注解 或者 value为false 则跳过拦截 
        	if (needVerify.typeOfAccess() == Permissions.METHOD_NEVER_VALIDATE) {
        		return true;
			} else if (needVerify.typeOfAccess() == Permissions.METHOD_LOGIN_VALIDATE) {
				if (sessionInfo != null) {
					logger.info("invocation.proceed");
					return true;
				} else {
					response.sendRedirect("/index.tml");
				}
			} else if (needVerify.typeOfAccess() == Permissions.METHOD_USER_PERMISSIONS_VALIDATE) {
				
			}
        }else{
    	    response.sendRedirect(request.getContextPath() + "index.html");  
        }
	    return false;  
	}
	
	/*@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	    // addPathPatterns 用于添加拦截规则
	    // excludePathPatterns 用户排除拦截
        //addPathPatterns("/**")对所有请求都拦截，但是排除了/toLogin和/login请求的拦截。
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static");
        super.addResourceHandlers(registry);
    }*/

}
